package cn.sciento.starter.social.wechat.connection;

import cn.sciento.starter.social.core.common.api.SocialApi;
import cn.sciento.starter.social.core.common.connect.SocialApiAdapter;
import cn.sciento.starter.social.core.common.connect.SocialConnectionFactory;
import cn.sciento.starter.social.core.common.connect.SocialServiceProvider;
import cn.sciento.starter.social.core.provider.Provider;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;

public class WechatConnectionFactory extends SocialConnectionFactory {
  public WechatConnectionFactory(Provider provider, SocialServiceProvider serviceProvider, SocialApiAdapter apiAdapter) {
    super(provider, serviceProvider, apiAdapter);
    setScope("snsapi_login");
  }
  
  protected String extractProviderUserId(AccessGrant accessGrant) {
    if (accessGrant instanceof WechatAccessGrant) {
      WechatAccessGrant wechatAccessGrant = (WechatAccessGrant)accessGrant;
      return wechatAccessGrant.getOpenId();
    } 
    return null;
  }
  
  public Connection<SocialApi> createConnection(AccessGrant accessGrant) {
    String providerUserId = extractProviderUserId(accessGrant);
    return (Connection<SocialApi>)new OAuth2Connection(getProviderId(), providerUserId, accessGrant.getAccessToken(), accessGrant
        .getRefreshToken(), accessGrant.getExpireTime(), (OAuth2ServiceProvider)getServiceProvider(), (ApiAdapter)new WechatApiAdapter(providerUserId));
  }
  
  public Connection<SocialApi> createConnection(ConnectionData data) {
    return (Connection<SocialApi>)new OAuth2Connection(data, (OAuth2ServiceProvider)getServiceProvider(), (ApiAdapter)new WechatApiAdapter(data.getProviderUserId()));
  }
}
